//
//  LoginViewController.m
//  mcosApp
//
//  Created by YaSha_Tom on 2018/12/12.
//  Copyright © 2018年 YaSha-Tom. All rights reserved.
//

#import "LoginViewController.h"
#import "AppDelegate.h"
#import "LoginView.h"
#import <ifaddrs.h>
#import <arpa/inet.h>

@interface LoginViewController ()<UITextFieldDelegate,UINavigationControllerDelegate>
@property (nonatomic, strong) LoginView *loginView;
@property (nonatomic,strong) NSMutableDictionary *parameter;
@property (nonatomic,strong) NSString * iphoneIP;
@end

@implementation LoginViewController
- (NSMutableDictionary *)parameter {
    if(!_parameter){
        _parameter = [NSMutableDictionary dictionary];
    }
    return _parameter;
}
- (LoginView *)loginView {
    if(!_loginView){
        _loginView = [[LoginView alloc]init];
        _loginView.passworkFiled.delegate = self;
        _loginView.nameFiled.delegate = self;
    }
    return _loginView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
     self.navigationController.delegate = self;
    [self.view addSubview:self.loginView];
    [self getIPAddress];
    @weakify(self);   //解决循环引用问题
    [[_loginView.loginButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        @strongify(self);
        [self doNetworking];
    }];
     [self monitorLogin];
}
#pragma mark - UINavigationControllerDelegate
// 将要显示控制器
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    // 判断要显示的控制器是否是自己
    BOOL isShowHomePage = [viewController isKindOfClass:[self class]];
    
    [self.navigationController setNavigationBarHidden:isShowHomePage animated:YES];
}
# pragma -- 检测密码和用户名是否输入
- (void)monitorLogin {
    @weakify(self)
    //用户名输入监听信号
    RACSignal *validAccountSignal = [_loginView.nameFiled.rac_textSignal map:^id(NSString  *value) {
        @strongify(self);
        [self.parameter setValue:value forKey:@"username"];
        return @(value.length > 0);
    }];
    
    //密码输入监听信号
    RACSignal *validPasswordSignal = [_loginView.passworkFiled.rac_textSignal map:^id(NSString *value) {
        @strongify(self);
        [self.parameter setValue:value forKey:@"password"];
        return @(value.length > 0);
    }];
    RACSignal *loginButtonSignal = [RACSignal combineLatest:@[validAccountSignal, validPasswordSignal] reduce:^id(NSNumber *accountValid, NSNumber *passwordValid) {
        return @([accountValid boolValue] && [passwordValid boolValue]);
    }];
    
    RAC(_loginView.loginButton, backgroundColor) = [loginButtonSignal map:^id(id value) {
        @strongify(self);
        if ([value boolValue]) {
            self.loginView.loginButton.enabled = YES;
            return [UIColor qmui_colorWithHexString:@"F55931"];
        } else {
            self.loginView.loginButton.enabled = NO;
            return  [UIColor lightGrayColor];
        }
    }];
}

- (void)doNetworking {
    NSString *urlString = [NSString stringWithFormat:@"%@%@",Domain,loginApi];
  
    [YSNetManager ys_request_GETWithUrlString:urlString isNeedCache:NO parameters:self.parameter successBlock:^(id response) {
        NSLog(@"成功%@",response);
        if ([response[@"code"]  isEqual: @0]) {
            [QMUITips showInfo:response[@"msg"] inView:self.view hideAfterDelay:1];
        }else{
            NSUserDefaults *de = [NSUserDefaults standardUserDefaults];
            [de setObject:response[@"data"][@"franId"] forKey:@"franId"];
            [de setObject:response[@"data"][@"id"] forKey:@"userId"];
            [de setObject:response[@"data"][@"desStr"] forKey:@"appkey"];
            [de setBool:YES forKey:@"login"];
            [de synchronize];

            AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
            [delegate enterTabBarController];
        }
    } failureBlock:^(NSError *error) {
        NSLog(@"失败%@",error);
    } progress:nil];
}
//获取IP
- (void)getIPAddress {
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0) {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while(temp_addr != NULL) {
            if(temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
    // Free memory
    freeifaddrs(interfaces);
    self.iphoneIP = address;
    NSUserDefaults *de = [NSUserDefaults standardUserDefaults];
    [de setObject:self.iphoneIP forKey:@"desIp"];
    [de synchronize];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
